<template>
    <el-form ref="ruleFormRef" style="max-width: 100%" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="账号" prop="account">
            <el-input v-model="ruleForm.account" :disabled="props.mode === 'edit'" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
            <el-input v-model="ruleForm.nickname" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar ">
            <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload"
                :auto-upload="false" accept="image/*" :on-change="handleAvatarChange">
                <!-- 优先级：新上传的预览 > 编辑模式下的原有头像 > 默认图标 -->
                <img v-if="avatarPreview" :src="avatarPreview" class="avatar" />
                <img v-else-if="ruleForm.avatar" :src="ruleForm.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="角色" prop="role">
            <el-select-v2 v-model="ruleForm.role" placeholder="选择角色" :options="options"
                :disabled="props.mode == 'edit'" />
        </el-form-item>
        <!-- <el-form-item label="Activity time" required>
            <el-col :span="11">
                <el-form-item prop="date1">
                    <el-date-picker v-model="ruleForm.date1" type="date" aria-label="Pick a date"
                        placeholder="Pick a date" style="width: 100%" />
                </el-form-item>
            </el-col>
        </el-form-item> -->
        <el-form-item>
            <div class="button-group">
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确认
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </div>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { storeFile } from '@/js/ts_fetch'
import { UploadProps, UploadFile } from 'element-plus'
import { FormInstance, FormRules } from 'element-plus'


// 定义父组件传入的props类型
interface UserInfoProps {
    mode: 'edit' | 'add'  // 联合类型约束模式
    initData: Partial<RuleForm>  // 允许部分字段（编辑时可能不全）
}

// 定义子组件发射的事件类型
type UserInfoEmits = {
    (e: 'close'): void
    (e: 'save', data: RuleForm): void
}
// 接收父组件参数（带类型约束）
const props = defineProps<UserInfoProps>()

// 暴露事件（带类型约束）
const emit = defineEmits<UserInfoEmits>()

// const imageUrl = ref<string>('')

// const handleAvatarSuccess: UploadProps['onSuccess'] = (
//     response,
//     uploadFile
// ) => {
//     imageUrl.value = URL.createObjectURL(uploadFile.raw)
// }

// 本地预览的图片URL
const avatarPreview = ref<string>('')
// 存储选择的文件对象
const avatarFile = ref<File | null>(null)

// 处理头像选择变化
const handleAvatarChange: UploadProps['onChange'] = (file: UploadFile) => {
    // 验证文件类型和大小
    if (!beforeAvatarUpload(file.raw!)) {
        return
    }
    // 生成本地预览URL
    avatarPreview.value = URL.createObjectURL(file.raw!)
    // 保存文件对象，等待提交时使用
    avatarFile.value = file.raw!
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
interface RuleForm {
    nickname: string
    avatar: string
    role: number
    account: string
    password: string
}

const ruleFormRef = ref<FormInstance | undefined>()
const ruleForm = reactive<RuleForm>({
    nickname: 'Hello',
    avatar: '',
    role: 2,
    account: '',
    password: ''
})

const rules = reactive<FormRules<RuleForm>>({
    nickname: [
        { required: true, message: 'Please input Activity name', trigger: 'blur' },
        { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    account: [
        { required: true, message: 'Please input account', trigger: 'blur' },
        { min: 3, max: 15, message: 'Length should be 3 to 15', trigger: 'blur' },
    ],
    password: [
        // 动态设置 required 规则
        {
            required: props.mode !== 'edit',
            message: 'Please input password',
            trigger: 'blur'
        },
        { min: 3, max: 15, message: 'Length should be 3 to 15', trigger: 'blur' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (!valid) {
            console.log('error submit!', fields)
            return

        }
    })

    if (avatarFile.value) {
        const resp = (await storeFile(avatarFile.value))
        ruleForm.avatar = resp.data
    } 
    emit('save', { ...ruleForm })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    emit('close')
}

// 监听初始化数据变化（带类型约束）
watch(
    () => props.initData,
    (newVal: Partial<RuleForm>) => {
        if (props.mode === 'edit' && newVal) {
            Object.assign(ruleForm, newVal)  // 编辑模式填充数据
        } else if (props.mode === 'add') {
            // 新增模式清空表单
            Object.keys(ruleForm).forEach(key => {
                ruleForm.nickname = ''
                ruleForm.avatar = ''
                ruleForm.role = 2  // 默认角色值
                ruleForm.account = ''
            })
        }
    },
    { immediate: true }
)
interface OptionItem {
    value: number
    label: string
}
const options: OptionItem[] = [
    { label: '管理员', value: 1 },
    { label: '普通用户', value: 2 },
    { label: '高级用户', value: 3 }
]


</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.button-group {
    display: flex;
    justify-content: center;
    gap: 40px;
    /* 按钮间距40px */
    width: 100%;
}
</style>